<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/10/27
 * Time: 下午5:16
 */

namespace common\helpers;


use Imagine\Imagick\Imagine;
use Yii;

class ImageHelper
{
    static $IMAGES_EXT = ['jpg','png','jpeg'];
    static $SVG_EXT = 'svg';
    
    /**
     * 生成或读取缩略图,并返回宽高等信息
     * @param $srcFile
     * @param int $targetWidth
     * @param int $targetHeight
     * @param bool $suffix
     * @return array
     */
    public static function makeImageThumbnail($srcFile, $targetWidth=228, $targetHeight=0, $suffix = true) {
        // 替换原路径中的缩略图路径
        $srcFile = str_replace('/nail/', '/', $srcFile);
        // 原图片路径
        $srcFullPath = Yii::getAlias('@parent') . $srcFile;
        // 文件扩展名
        $ext = strtolower(pathinfo($srcFullPath, PATHINFO_EXTENSION));
        
        /**
         * 文件名不合规则
         * 文件不存在 并且 不是开发环境 并且 不是svg
         * 不处理直接返回
         */
        
        if( !in_array($ext, self::$IMAGES_EXT) || ( !($isFile = file_exists($srcFullPath)) && YII_ENV != 'dev' && $ext != self::$SVG_EXT ) ){
            return ['w'=>0, 'h'=>0, 'file'=>$srcFile];
        }
        
        //处理 svg
        if($ext == self::$SVG_EXT) {
            $filecontent = file_get_contents($srcFullPath);
            $matches = [];
            $w=$h=0;
            if(preg_match('/width=\"([\d\.]+)px\"/i', $filecontent, $matches)) {
                $w = intval($matches[1]);
            }
            if(preg_match('/height=\"([\d\.]+)px\"/i', $filecontent, $matches)) {
                $h = intval($matches[1]);
                if($w>0) {
                    $h = $h*($targetWidth/$w);
                }
            }
            return ['w'=>$targetWidth, 'h'=>$h, 'file'=>$srcFile];
        }

        // 文件名
        $filename = pathinfo($srcFullPath, PATHINFO_FILENAME);
        // 指向缩略图目录
        $nailDir = dirname($srcFile)."/nail";
        $nailFile = $suffix ? sprintf("%s/%s_%s.%s", $nailDir, $filename, $targetWidth, $ext) : sprintf("%s/%s.%s", $nailDir, $filename, $ext);
        // 缩略图全路径
        $nailPath = Yii::getAlias('@parent') . $nailFile ;
        
        // 如果是开发模式并且文件在本地不存在
        if( YII_ENV == 'dev' && !$isFile ){
            $srcFullPath = Yii::$app->params['tubangzhu_domain'] . $srcFile;
        }

        // 如果缩略图存在获取图片信息
        if( file_exists( $nailPath) ) {
            $imageInfo = getimagesize($nailPath);
            return [ 'w' => $imageInfo[0], 'h' => $imageInfo[1], 'file' => $nailFile];
        }
        
        // 创建目录
        if(!is_dir(Yii::getAlias('@parent') . $nailDir)) {
            mkdir(Yii::getAlias('@parent') . $nailDir, 0777, true);
        }
        
        try {
            $image = new Imagine();
            $size = $image->open( $srcFullPath )
                ->resize(new Box($targetWidth, $targetHeight))
                ->save($nailPath)
                ->getSize();
    
            return [ 'w' => $size->getWidth(), 'h' => $size->getHeight(), 'file' => $nailFile  ];
        } catch(\Exception $e){
            return ['w'=>0, 'h'=>0, 'file'=>$srcFile];
        }


    }
    
}